import Taro, { Component } from '@tarojs/taro'
import { Button, Image, ScrollView, Text, View } from '@tarojs/components'
import classNames from 'classnames'
import './update.scss'
import { OSS, APP_SYSTEM_INFO } from '@/config/config'
import { getLastVersion } from '@/api/versionApi'
// import { LoadingRing } from '@/components/index'

const { navBarHeight } = APP_SYSTEM_INFO
const updateManager = wx.getUpdateManager()
export default class VersionUpdate extends Component {
  state: any
  static options = {
    addGlobalClass: true
  }

  constructor() {
    super(...arguments)
    this.state = {
      info: '',
      loading: false,
      isRenew: false,
      showView: false
    }
  }

  componentDidShow () {
    updateManager.onCheckForUpdate(res => {
      res.hasUpdate && this.setState({
        showView: true
      }, () => {
        this.getUpdateInfo()
      })
    })
  }

  //  获取小程序更新信息
  getUpdateInfo () {
    getLastVersion().then(res => {
      const { data } = res
      this.setState({
        info: data.content,
        isRenew: true,
      })
    }).catch(() => {
      this.setState({
        isRenew: true,
      })
    })
  }

  //  立即更新
  applyUpdateReady() {
    this.setState({
      loading: true
    })

    updateManager.onUpdateReady(() => { // 新的版本已经下载好
      setTimeout(() => {
        updateManager.applyUpdate()
      }, 500)
    })


    updateManager.onUpdateFailed(() => { // 新的版本下载失败
      this.setState({
        status: 0,
        loading: false
      })
      wx.showModal({
        title: '已经有新版本了哟~',
        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
        showCancel: false
      })
    })
  }

  render() {
    const { showView, loading, isRenew, info } = this.state
    // @ts-ignore
    return showView && (<View className='version-update' catchtouchmove>
      <View className={classNames('fy-transition fade fy-mask', isRenew && 'show')}/>
      <View className={classNames('fy-transition slide-bottom fy-full f-g-5', isRenew && 'show')} style={{top: `${navBarHeight}px`}}>
        <View className='layer-box'>
          <View className='layer-bg'>
            <Image src={`${OSS}/system/image/app_update_bg.png`}/>
          </View>
          <View className='layer-body'>
            <View className='update-title f-g-5'>
              <View className='title-text'>版本更新</View>
            </View>
            <ScrollView className='update-scroll'>
              <Text decode className='update-content'>{info}</Text>
            </ScrollView>
          </View>
          <View className='layer-bottom'>
            <Button disabled={loading} className='layer-button f-g-5' onClick={this.applyUpdateReady.bind(this)}>
              {/*{loading && <View className='m-r-20'><LoadingRing color="#fff"/></View>}*/}
              立即更新
            </Button>
          </View>
        </View>
      </View>
    </View>)
  }
}
